package actions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.EventModel;
import model.VenueModel;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import db.DBModel;
import forms.EventFormInsertUpdate;

public class EditEventAction extends Action{
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request,HttpServletResponse response){
	try{
		DBModel db = new DBModel();

		int eventId=Integer.parseInt(request.getParameter("id"));
		
		EventModel event = db.getEvent(eventId);
		EventFormInsertUpdate f = (EventFormInsertUpdate) form;
		f.setEventId(String.valueOf(eventId));
		f.setEventName(event.getEventName());
		f.setDate(event.getDate());
		f.setTime(event.getTime());
		f.setDesc(event.getDescription());
		f.setMinCapacity(event.getMinCapacityString());
		
		int venueId = event.getVenueId();
		String venueName = db.getVenueName(venueId);
		//Add venue list ass collection (because of struts) - NB! Should add selected venue first!
		ArrayList<VenueModel> venues = db.getAllVenues();
		f.setVenueList(getVenueListCollection(venues, venueId, venueName));
		
		if(event.getMaxCapacity()==-1){
			f.setMaxCapacity("");
		}
		else{
			f.setMaxCapacity(event.getMaxCapacityString());
		}
		
		//request.setAttribute("venueList", db.getAllVenues());
		//request.setAttribute("eventId", eventId);
		
		db.commit();
		db.close();

		return mapping.findForward("success");
		
		}catch (Exception e){
			e.printStackTrace();
			request.setAttribute("error", e.toString());
			return mapping.findForward("fail");
		}	
	}
	
	private Collection getVenueListCollection(ArrayList<VenueModel> venues, int venueId, String venueName){
		Collection venueList=new Vector(venues.size());
		//Adds the already selected venue first
		venueList.add(new LabelValueBean(venueName, String.valueOf(venueId)));
		for(int i=0;i<venues.size();i++){
			if(venues.get(i).getId()!=venueId){
				venueList.add( new LabelValueBean(venues.get(i).getName(),String.valueOf(venues.get(i).getId())) );
			}
		}
		return venueList;
	}
}
